package com.hjy.member.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.hjy.common.utils.R;
import com.hjy.member.dao.MemberLevelDao;
import com.hjy.member.entity.MemberEntity;
import com.hjy.member.entity.MemberLevelEntity;
import com.hjy.member.exceptiion.MyException;
import com.hjy.member.vo.LoginVo;
import com.hjy.member.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjy.common.utils.PageUtils;
import com.hjy.common.utils.Query;

import com.hjy.member.dao.MemberDao;
import com.hjy.member.service.MemberService;

import javax.servlet.http.HttpSession;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(RegisterVo registerVo) throws MyException {
        MemberEntity memberEntity = new MemberEntity();
        // 1. 首先设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(memberLevelEntity.getId());

        // 2. 设置用户名和电话号码
        long count = this.count(new QueryWrapper<MemberEntity>().eq("username", registerVo.getUsername()));
        if (count > 0) {
            throw new MyException("用户名重复");
        } else {
            memberEntity.setUsername(registerVo.getUsername());
        }

        count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", registerVo.getPhone()));
        if (count > 0) {
            throw new MyException("手机号重复");
        } else {
            memberEntity.setMobile(registerVo.getPhone());
        }

        // 3. 设置密码
        memberEntity.setPassword(registerVo.getPassword());

        // 4. 保存
        this.save(memberEntity);
    }

    @Override
    public R login(LoginVo loginVo, HttpSession session) {
        MemberEntity memberEntity = baseMapper.findUser(loginVo.getUsername(), loginVo.getPassword());
        if (memberEntity != null) {
            session.setAttribute("loginUser",memberEntity);
            return R.ok();
        } else {
            return R.error();
        }

    }

    @Override
    public MemberEntity oauthLogin(Map<String, String> map) {
        // 1. 首先获取 token 和 uid, expires_in
        String token = map.get("access_token");
        String uid = map.get("uid");
        Long expiresIn = Long.parseLong(map.get("expires_in"));

        // 2. 判断是否有这个用户, 如果没有就注册一个
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (memberEntity != null) {
            // 说明是有这个用户的
            memberEntity.setAccessToken(token);
            memberEntity.setExpiresIn(expiresIn);
            this.updateById(memberEntity);

            return memberEntity;
        } else {
            // 没有这个用户, 需要注册一个
            memberEntity = new MemberEntity();
            // 首先获取微博用户的数据
            HashMap<String, Object> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("access_token", token);
            stringStringHashMap.put("uid", uid);

            HttpResponse execute = HttpRequest.get("https://api.weibo.com/2/users/show.json")
                    .form(stringStringHashMap)
                    .execute();
            if (execute.getStatus() == 200) {
                String body = execute.body();
                HashMap<String, Object> hashMap = JSONUtil.toBean(body, new TypeReference<HashMap<String, Object>>() {
                }, true);
                memberEntity.setNickname((String) hashMap.get("screen_name"));
                memberEntity.setGender(hashMap.get("gender").equals("m") ? 0 : 1);
                memberEntity.setUsername((String) hashMap.get("screen_name"));
                memberEntity.setLevelId(1L);
            }
            memberEntity.setAccessToken(token);
            memberEntity.setExpiresIn(expiresIn);
            memberEntity.setUid(uid);
            this.save(memberEntity);
            return memberEntity;
        }
    }

}